package server;

/**
 * Makes Math for PrimeCalculation
 * @author cdt-sb
 *
 */
public class AtkinSieveArray {

    public static int count(final boolean[] buffer) {
        int counter = 0;
        for(int i = 2; i < buffer.length; ++i) {
            if(buffer[i]) {
                counter++;
            }
        }
        return counter;
    }
    
    /**
     * Sieves a boolean buffer to primes
     * @param buffer
     */
    public static void sieve(final boolean[] buffer) {
        int end = buffer.length;
        double limit = Math.sqrt(end);

        int n, x, x2, x2_3, y, y2;
        int k, i, m;

        for (x = 1; x <= limit; ++x) {
            x2 = x * x;
            x2_3 = 3 * x2;

            for (y = 1; y <= limit; ++y) {
                y2 = y * y;
                n = 4 * x2 + y2;
                if ((n < end) && (n % 12 == 1 || n % 12 == 5)) {
                    buffer[n] = !buffer[n];
                }

                n = x2_3 + y2; /* 3x^2 + y^2 */
                if ((n < end) && (n % 12 == 7)) {
                    buffer[n] = !buffer[n];
                }

                n = x2_3 - y2; /* 3x^2 - y^2 */
                if ((x > y) && (n < end) && (n % 12 == 11)) {
                    buffer[n] = !buffer[n];
                }
            }
        }

        for (n = 5; n <= limit; n += 2) {
            if (buffer[n]) {
                k = n * n;
                for (i = 1, m = k; m < end; i += 2, m = i * k) {
                    buffer[m] = false;
                }
            }
        }

        buffer[3] = true;
        buffer[2] = true;
    }

}